package com.tomorrow.weather.dbmanager;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import android.util.Log;

import com.tomorrow.weather.entity.City;

public class DBManager
{
	private final int BUFFER_SIZE = 400000;
	public static final String DB_NAME = "base.db";
	public static final String PACKAGE_NAME = "com.tomorrow.weather.ui";
	public static final String DB_PATH = "/data"
			+ Environment.getDataDirectory().getAbsolutePath() + "/"
			+ PACKAGE_NAME;
	private SQLiteDatabase database;
	private Context context;

	public DBManager(Context context)
	{
		this.context = context;
	}

	public void openDatabase()
	{
		this.database = this.openDatabase(DB_PATH + "/" + DB_NAME);
	}

	private SQLiteDatabase openDatabase(String dbfile)
	{
		try
		{
			if (!(new File(dbfile).exists()))
			{
				InputStream is = this.context.getAssets().open(DB_NAME);
				FileOutputStream fos = new FileOutputStream(dbfile);
				byte[] buffer = new byte[BUFFER_SIZE];
				int count = 0;
				while ((count = is.read(buffer)) > 0)
				{
					fos.write(buffer, 0, count);
				}
				fos.close();
				is.close();
			}
			SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile,
					null);
			return db;
		}
		catch (FileNotFoundException e)
		{
			Log.e("Database", "File not found");
			e.printStackTrace();
		}
		catch (IOException e)
		{
			Log.e("Database", "IO exception");
			e.printStackTrace();
		}
		return null;
	}

	public ArrayList<City> getCities(String keyWord)
	{
		Cursor cursor = database.rawQuery(
				"select * from geo where name_cn like '%" + keyWord + "%'",
				null);
		if (cursor != null)
		{
			ArrayList<City> cities = new ArrayList<City>();
			if (cursor.moveToFirst())
			{
				do
				{

					String cityId = cursor.getString(cursor
							.getColumnIndex("area_id"));
					String cityName = cursor.getString(cursor
							.getColumnIndex("name_cn"));
					City city = new City();
					city.setCityId(cityId);
					city.setCityName(cityName);
					cities.add(city);
				}
				while (cursor.moveToNext());
			}
			return cities;
		}
		return null;

	}

	public void closeDatabase()
	{
		this.database.close();
	}
}
